package index.metadata;

import static storage.metadata.TableMgr.MAX_NAME;

import java.util.HashMap;
import java.util.Map;

import storage.metadata.TableMgr;
import storage.record.RecordFile;
import storage.record.Schema;
import storage.record.TableInfo;
import storage.tx.Transaction;

public class IndexMgr {
	private static int nextIdxNum = 0;
	private TableInfo ti;
	
	public IndexMgr(boolean isNew, TableMgr tblmgr, Transaction tx){
		if(isNew){
			Schema sch = new Schema();
			sch.addStringField("tablename", MAX_NAME);
			sch.addStringField("fieldname", MAX_NAME);
			sch.addIntField("indexnumber");
			tblmgr.createTable("idxcat", sch, tx);
		}
		ti = tblmgr.getTableInfo("idxcat", tx);
	}
	
	public void createIndex(String tblname, String fldname, Transaction tx){
		int idxnum = nextIndexNumber();
		RecordFile rf = new RecordFile(ti, tx);
		rf.insert();
		rf.setString("tablename", tblname);
		rf.setString("fieldname", fldname);
		rf.setInt("indexnumber", idxnum);
		rf.close();
	}
	
	public Map<String, IndexInfo> getIndexInfo(String tblname, Transaction tx){
		Map<String, IndexInfo> result = new HashMap<String, IndexInfo>();
		RecordFile rf = new RecordFile(ti, tx);
		while(rf.next()){
			if (rf.getString("tablename").equals(tblname)){
				String fldname = rf.getString("fieldname");
				int indexnum = rf.getInt("indexnumber");
				IndexInfo ii = new IndexInfo(tblname, fldname, indexnum, tx);
				result.put(fldname, ii);
			}
		}
		rf.close();
		return result;
	}

	
	private static synchronized int nextIndexNumber(){
		nextIdxNum++;
		return nextIdxNum;
	}
}
